﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

using FluentValidation;

using CloudSoft.Extensions;

namespace ERPStore.Validators
{
	public static class EmailValidator
	{
		public static bool IsValidEmail(string email)
		{
			if (email.IsNullOrTrimmedEmpty())
			{
				return false;
			}
			return System.Text.RegularExpressions.Regex.Match(email, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*").Success;
		}
	}

	public static class PhoneNumberValidator
	{
		public static bool IsValidPhoneNumber(string phoneNumber)
		{
			if (phoneNumber.IsNullOrTrimmedEmpty())
			{
				return false;
			}
			var match = System.Text.RegularExpressions.Regex.Match(phoneNumber, @"^(\+[\s\d]{6,}|[\s\d]{6,})");
			return match.Success;
		}
	}

	public static class ValidatorExtensions
	{
		public static IRuleBuilderOptions<T, TElement> PhoneNumber<T, TElement>(this IRuleBuilder<T, TElement> ruleBuilder, ERPStore.Models.Country country)
		{
			return ruleBuilder.SetValidator(new Validators.PhoneNumberValidator<T, TElement>(country));
		}

		public static IRuleBuilderOptions<T, TElement> PhoneNumber<T, TElement>(this IRuleBuilder<T, TElement> ruleBuilder, Func<T, ERPStore.Models.Country> predicate)
		{
			return ruleBuilder.SetValidator(new Validators.PhoneNumberValidator<T,TElement>(predicate));
		}

		public static IRuleBuilderOptions<T, TElement> NotNullOrTrimmedEmpty<T, TElement>(this IRuleBuilder<T, TElement> ruleBuilder)
		{
			return ruleBuilder.SetValidator(new Validators.NotNullOrTrimmedEmptyValidator<TElement>());
		}

		public static IRuleBuilderOptions<T, TElement> ZipCode<T, TElement>(this IRuleBuilder<T, TElement> ruleBuilder, Func<T, ERPStore.Models.Country> predicate)
		{
			return ruleBuilder.SetValidator(new Validators.ZipCode<T,TElement>(predicate));
		}

		public static List<global::ERPStore.Models.BrokenRule> ToBrokenRuleList(this global::FluentValidation.Results.ValidationResult validationResult)
		{
			var result = new List<global::ERPStore.Models.BrokenRule>();
			foreach (var item in validationResult.Errors)
			{
				var brokenRule = result.SingleOrDefault(i => i.PropertyName == item.PropertyName);
				if (brokenRule == null)
				{
					brokenRule = new global::ERPStore.Models.BrokenRule();
					brokenRule.PropertyName = item.PropertyName;
				}
				brokenRule.ErrorList.Add(item.ErrorMessage);
				result.Add(brokenRule);
			}
			return result;
		}


	}
}
